package com.bmt.pos.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.bmt.common.LoginUser;
import com.bmt.core.BaseContoller;
import com.bmt.exception.ServiceException;
import com.bmt.pos.service.UserModuleService;
import com.bmt.pos.service.UserService;

@Controller
public class UserLoginContoller extends BaseContoller {
	@Autowired
	private UserService userService;
	@Autowired
	private UserModuleService userModuleService;
	
	

	@RequestMapping(value = "saveLogin.htm", method = RequestMethod.POST)
	public ModelAndView saveLogin(HttpSession session, String userName, String pwd, ModelMap modelMap) {
		if (userName != null) {
			try {
				LoginUser loginUser = userService.login(userName, pwd);
				if (loginUser == null) {
					return new ModelAndView("login", COMMON_FAIL_ALERT_KEY, "User or Password  Error!");
				}
				session.setAttribute(LOGIN_USER, loginUser);
			} catch (ServiceException e) {
				e.printStackTrace();
			}
		}
		return new ModelAndView("redirect:main.htm");
	}

	@RequestMapping(value = "main.htm")
	public String signuoSucc(HttpSession session, ModelMap map) throws ServiceException {
		LoginUser loginUser = (LoginUser) session.getAttribute(LOGIN_USER);
		if (loginUser == null) {
			return "redirect:login.htm";
		}
		map.put("user_Module_list", loginUser.getUserModuleList());
		map.put("loginUser", loginUser);
		return "main";
	}

	@RequestMapping("logout.htm")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:login.htm";
	}
	
	@RequestMapping(value = "userChange/{id}.htm", method = RequestMethod.GET)
	public String userChange(HttpSession session, @PathVariable Integer id) throws ServiceException {
		LoginUser loginUser = (LoginUser) session.getAttribute(LOGIN_USER);
		userModuleService.userChange(loginUser,id);
		return "redirect:/main.htm";
	}

}
